import axios from 'axios'
import store from '@store'
import { getToken,getOtherCookie,removeToken,setToken } from '@utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 6000 *30 // request timeout
})

// request interceptor
service.interceptors.request.use(

  config => {
	  const token = getToken()
	// config.headers['Content-Type'] = 'application/json'
    if (token) {
      config.headers['x-token'] = token
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
	if(res.code == 200){
		return res
	} else if(res.code === 401 || res.code === 403 || res.code === 504 || res.code === 500) {
		return res
		// return Promise.reject(new Error(res.message || 'Error'))
	} else{
		return res
	}
  },
  error => {
    
  }
)
// 分享
const shareService = axios.create({
  baseURL: process.env.VUE_APP_SHARE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
shareService.interceptors.request.use(

  config => {
	// config.headers['Content-Type'] = 'application/json'
    if (localStorage.getItem(process.env.VUE_APP_TOKEN_KEY)) {
      config.headers['x-token'] = localStorage.getItem(process.env.VUE_APP_TOKEN_KEY)
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
shareService.interceptors.response.use(
  response => {
    const res = response.data
	if(res.code == 200){
		return res
	} else if(res.code === 401 || res.code === 403 || res.code === 504 || res.code === 500) {
		return res
		// return Promise.reject(new Error(res.message || 'Error'))
	} else{
		return res
	}
  },
  error => {
    
  }
)

export {
	service,
	shareService
}
